import React, {useEffect, useRef, useState} from 'react';
import {Download, FileText, Trash2, Upload, X} from 'lucide-react';
import {Req, UploadFile} from "../../util/fetch.ts";

interface Document {
    id: number;
    name: string;
    size: string;
    type: string;
    crtTime: string;
    url: string;
}

interface Training {
    id: number;
    title: string;
}

interface DocumentManageModalProps {
    training: Training;
    onClose: () => void;
}

export default function DocumentManageModal({training, onClose}: DocumentManageModalProps) {
    const [documents, setDocuments] = useState<Document[]>([]);
    const fileInputRef = useRef<HTMLInputElement | null>(null); // 创建文件输入引用

    const getFileType = (name: string) => {
        // .pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx
        if (name.endsWith('.pdf')) {
            return 'pdf';
        } else if (name.endsWith('.doc') || name.endsWith('.docx')) {
            return 'word';
        } else if (name.endsWith('.xls') || name.endsWith('.xlsx')) {
            return 'excel';
        } else if (name.endsWith('.ppt') || name.endsWith('.pptx')) {
            return 'ppt';
        }
        return 'unknown';
    }

    const handleDeleteDocument = (id: number) => {
        setDocuments(documents.filter(doc => doc.id !== id));
    };

    const downloadFile = (url: string, name: string) => {
        const link = document.createElement('a');
        link.href = url;
        link.download = name; // 设置下载的文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };

    const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (!files) return;
        const res = await UploadFile(2, files[0])
        setDocuments([...documents, {
            id: null,
            url: res.data.url,
            name: res.data.fileName,
            size: Math.floor(files[0].size / 1024) + 'KB',
            type: getFileType(res.data.fileName),
            crtTime: new Date().toLocaleString(),
        }]);
        console.log('handleFileChange', files, res);
    };

    const handleSelectFileClick = () => {
        if (fileInputRef.current) {
            fileInputRef.current.click(); // 触发文件输入的点击事件
        }
    };

    const saveDocuments = async () => {
        console.log('saveDocuments', documents);
        const list = []
        let i = 0
        documents.forEach(item => {
            list.push({
                name: item.name,
                trainId: training.id,
                url: item.url,
                docType: item.type,
                sort: i,
                docSize: item.size,
            })
            i++;
        })
        const res = await Req('/bsTrainDocument/add', {
            method: 'POST',
            body: {
                trainId: training.id,
                list
            },
            headers: undefined
        })
        if (res.success) {
            alert(res.message)
            onClose()
        } else {
            alert(res.message)
        }
    };

    const queryList = async (id) => {
        const res = await Req(`/bsTrainDocument/list?trainId=${id}`)
        if (res.success) {
            setDocuments(res.data.map((item) => {
                return {
                    id: item.id,
                    name: item.name,
                    url: item.url,
                    type: item.docType,
                    size: item.docSize,
                    trainId: item.trainId,
                }
            }));
        } else {
            alert(res.message)
        }
    };

    useEffect(() => {
        queryList(training.id)
    }, [])
    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
            <div className="bg-white rounded-lg w-full max-w-4xl mx-4 max-h-[90vh] flex flex-col">
                <div className="flex items-center justify-between p-4 border-b">
                    <h3 className="text-lg font-semibold text-gray-900">资料管理</h3>
                    <button onClick={onClose}>
                        <X className="w-6 h-6 text-gray-500"/>
                    </button>
                </div>

                <div className="p-6 flex-1 overflow-y-auto">
                    {/* 上传区域 */}
                    <div className="mb-6">
                        <div className="border-2 border-dashed rounded-lg p-6 text-center">
                            <Upload className="mx-auto h-12 w-12 text-gray-400"/>
                            {/*<p className="mt-2 text-gray-600">拖拽文件到此处或点击上传</p>*/}
                            <p className="text-sm text-gray-500">
                                支持 PDF、Word、Excel、PPT 等文档格式
                            </p>
                            <input
                                type="file"
                                className="hidden"
                                accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx"
                                multiple
                                ref={fileInputRef}
                                onChange={handleFileChange}
                            />
                            <button
                                onClick={handleSelectFileClick}
                                className="mt-4 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">
                                选择文件
                            </button>
                        </div>
                    </div>

                    {/* 文档列表 */}
                    <div className="space-y-4">
                        {documents.map(doc => (
                            <div
                                key={doc.id}
                                className="flex items-center justify-between p-4 bg-gray-50 rounded-lg group hover:bg-gray-100"
                            >
                                <div className="flex items-center space-x-4">
                                    <div className="p-3 bg-blue-100 rounded-lg">
                                        <FileText className="w-6 h-6 text-blue-600"/>
                                    </div>
                                    <div>
                                        <h4 className="font-medium text-gray-900">{doc.name}</h4>
                                        <div className="flex items-center space-x-4 mt-1 text-sm text-gray-500">
                                            <span>大小：{doc.size}</span>
                                            <span>上传时间：{doc.crtTime}</span>
                                        </div>
                                    </div>
                                </div>
                                <div className="flex items-center space-x-2">
                                    <button
                                        onClick={() => downloadFile(doc.url, doc.name)}
                                        className="p-2 text-gray-400 hover:text-blue-500 opacity-0 group-hover:opacity-100 transition-opacity"
                                        title="下载"
                                    >
                                        <Download className="w-5 h-5"/>
                                    </button>
                                    <button
                                        onClick={() => handleDeleteDocument(doc.id)}
                                        className="p-2 text-gray-400 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity"
                                        title="删除"
                                    >
                                        <Trash2 className="w-5 h-5"/>
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

                <div className="flex justify-end space-x-3 p-4 bg-gray-50 rounded-b-lg">
                    <button
                        onClick={onClose}
                        className="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg"
                    >
                        关闭
                    </button>
                    <button
                        onClick={saveDocuments}
                        className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">
                        保存
                    </button>
                </div>
            </div>
        </div>
    );
}